package com.sansan.qiangji.controller.warehouse;


import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.sansan.qiangji.dto.PushOrderDetailExcelDto;
import com.sansan.qiangji.dto.PushOrderExcelDto;
import com.sansan.qiangji.enums.ResultEnum;
import com.sansan.qiangji.exception.ServiceException;
import com.sansan.qiangji.form.warehouse.PushOrderAddForm;
import com.sansan.qiangji.form.warehouse.PushOrderEditForm;
import com.sansan.qiangji.form.warehouse.PushOrderListForm;
import com.sansan.qiangji.realize.warehouse.PushOrderExcelListener;
import com.sansan.qiangji.realize.warehouse.PushOrderReal;
import com.sansan.qiangji.resultVO.ResultVO;
import com.sansan.qiangji.utils.DateUtil;
import com.sansan.qiangji.utils.ResultVOUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@CrossOrigin()
@RestController
@Slf4j
@RequestMapping("/pushOrder")
public class PushOrderController {

    @Autowired
    private PushOrderReal pushOrderReal;


    @PostMapping("/addPushOrder")
    public ResultVO<Object> addPushOrder(@Valid @RequestBody PushOrderAddForm pushOrderAddForm, BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            log.error("【入库单新增】参数不正确，pushOrderAddForm={}",pushOrderAddForm);
            throw new ServiceException(ResultEnum.PARAM_ERROR.getCode(), Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage());
        }
        pushOrderReal.addPushOrder(pushOrderAddForm);
        return ResultVOUtil.success(null);
    }

    @PostMapping("/getPushOrderList")
    public ResultVO<Object> getPushOrderList(@Valid @RequestBody PushOrderListForm form, BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            log.error("【入库单查询】参数不正确，pushOrderAddForm={}",form);
            throw new ServiceException(ResultEnum.PARAM_ERROR.getCode(), Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage());
        }
        return ResultVOUtil.success(pushOrderReal.pushOrderList(form));
    }

    @PostMapping("/editPushOrder")
    public ResultVO<Object> editPushOrder(@Valid @RequestBody PushOrderEditForm pushOrderEditForm, BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            log.error("【入库单修改】参数不正确，pushOrderAddForm={}",pushOrderEditForm);
            throw new ServiceException(ResultEnum.PARAM_ERROR.getCode(), Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage());
        }
        pushOrderReal.editPushOrder(pushOrderEditForm);
        return ResultVOUtil.success(null);
    }

    @PostMapping("/deletePushOrder")
    public ResultVO<Object> deletePushOrder(@RequestParam(value = "pushOrderId") Integer pushOrderId){
        pushOrderReal.deletePushOrder(pushOrderId);
        return ResultVOUtil.success(null);
    }

    @GetMapping("/downloadTemplate")
    public void downloadTemplate(HttpServletResponse response) throws Exception {
        ClassPathResource classPathResource = new ClassPathResource("excelTemplate/pushOrder.xls");
        InputStream inputStream = classPathResource.getInputStream();
        Workbook workbook = new HSSFWorkbook(inputStream);
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("content-Disposition", "attachment;filename=" + URLEncoder.encode("pushOrder.xls", "utf-8"));
        response.setHeader("Access-Control-Expose-Headers", "content-Disposition");
        OutputStream outputStream = response.getOutputStream();
        workbook.write(outputStream);
        outputStream.flush();
        outputStream.close();
    }

    @GetMapping("/downLoadPushOrder")
    public void downLoadPushOrder(HttpServletResponse response, @RequestParam(name = "pushOrderCode") String pushOrderCode) throws Exception {
        List<PushOrderDetailExcelDto> pushOrderDetailExcelDtos = pushOrderReal.getAllPushOrderDto(pushOrderCode);
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        response.setHeader("content-Disposition", "attachment;filename=" + URLEncoder.encode("pushOrder.xls", "utf-8"));
        response.setHeader("Access-Control-Expose-Headers", "content-Disposition");
        EasyExcel.write(response.getOutputStream(), PushOrderDetailExcelDto.class).excelType(ExcelTypeEnum.XLS).sheet("sheet1").doWrite(pushOrderDetailExcelDtos);
        response.getOutputStream().flush();
        response.getOutputStream().close();
    }

    @GetMapping("/exportPushOrderByDate")
    public void exportPushOrderByDate(HttpServletResponse response, @RequestParam(name = "startTime") String startTime, @RequestParam(name = "endTime") String endTime) throws Exception {
        Date startTime1 = DateUtil.string2Date(startTime, "yyyy-MM-dd");
        Date endTime1 = DateUtil.string2Date(endTime, "yyyy-MM-dd");
        List<PushOrderDetailExcelDto> pushOrderDetailExcelDtos = pushOrderReal.getAllPushOrderDtoByDate(startTime1, endTime1);
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        response.setHeader("content-Disposition", "attachment;filename=" + URLEncoder.encode("pushOrder.xls", "utf-8"));
        response.setHeader("Access-Control-Expose-Headers", "content-Disposition");
        EasyExcel.write(response.getOutputStream(), PushOrderDetailExcelDto.class).excelType(ExcelTypeEnum.XLS).sheet("sheet1").doWrite(pushOrderDetailExcelDtos);
        response.getOutputStream().flush();
        response.getOutputStream().close();
    }

    @PostMapping("/upLoadPushOrderExcel")
    public ResultVO<Object> upLoadPushOrderExcel(@RequestParam("file") MultipartFile file) throws IOException {
        try {
            EasyExcel.read(file.getInputStream(), PushOrderExcelDto.class, new PushOrderExcelListener(pushOrderReal)).excelType(ExcelTypeEnum.XLS).sheet().doRead();
        }catch (IOException e) {
            log.error("【上传入库单表格】入库单表格文件解析失败");
            throw e;
        }
        return ResultVOUtil.success(null);
    }
}
